<template>
  <div class="search">
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        v-model="keywords"
        placeholder="大家都在搜~~~"
        shape="round"
        @input="search"
      >
        <template #left>
          <div class="back">
            <van-icon name="arrow-left" @click="goBack" />
          </div>
        </template>
      </van-search>
    </form>

    <!-- 搜索建议 -->
    <div class="suggestlist" v-show="keywords === '' ? false : true">
      <div
        class="suggestlistbox"
        v-for="(item, index) in suggestData"
        :key="index"
        @click="
          playAudio(
            item.id,
            item.artists[0].img1v1Url,
            item.name,
            item.artists[0].name,
            item.artists[0].id
          )
        "
      >
        <div class="suggesticon">
          <van-icon name="search" />
        </div>

        <div class="suggestname">{{ item.name }}</div>
      </div>
    </div>

    <!-- 搜索记录 -->
    <div class="records" v-show="keywordsData.length === 0 ? false : true">
      <div class="title">
        历史记录
        <div class="recordsright" @click="clearAll">
          <van-icon name="delete-o" />
        </div>
      </div>

      <div
        class="recordsbox"
        v-for="(item, index) in keywordsData"
        :key="index"
      >
        <div class="recordsleft">
          <van-icon name="clock-o" />
        </div>

        <div class="recordsname">
          {{ item.title }}
        </div>

        <div class="recordsright" @click="removeOne(index)">
          <van-icon name="cross" />
        </div>
      </div>
    </div>

    <!-- 热搜榜 -->
    <div class="hot">
      <div class="title">热搜榜</div>

      <div class="hotbox" v-for="(v, i) in hotData" :key="i">
        <div class="hotlist" v-for="(v1, i1) in v.ShowhotData" :key="i1">
          <!-- 歌名 -->
          <div class="name">
            {{ v1.searchWord }}
            <div class="icon" v-show="v1.iconUrl !== null">
              <img :src="v1.iconUrl" alt="" />
            </div>
          </div>

          <!-- 简介 -->
          <div class="txt">{{ v1.content }}</div>
        </div>

        <!-- 显示更多 -->
        <div class="showmore" v-if="v.showMore" @click="showMorehotData(v)">
          显示更多热搜
          <van-icon name="arrow-down" />
        </div>
      </div>
    </div>

    <!-- 热门歌手 -->
    <div class="hotsonger">
      <div class="title">热门歌手</div>

      <div
        class="songerlist"
        v-for="(item, index) in hotSongerData"
        :key="index"
        @click="viewSonger(item.id)"
      >
        <!-- 歌手图片 -->
        <div class="songerphoto">
          <van-image :src="item.picUrl" lazy-load>
            <template v-slot:loading>
              <van-loading type="spinner" size="20" />
            </template>
          </van-image>
        </div>

        <!-- 名字 -->
        <div class="songername">{{ item.name }}</div>

        <!-- 关注 -->
        <div class="go">
          <van-icon name="arrow" size="20px" />
        </div>
      </div>
    </div>

    <!-- 播放器 -->
    <Playbox></Playbox>
  </div>
</template>

<script>
import Playbox from "../components/Playbox.vue";
import { mapState, mapMutations } from "vuex";
export default {
  name: "Search",

  components: {
    Playbox,
  },

  data() {
    return {
      //定时器序号
      timer: null,

      //搜索关键词
      keywords: "",

      //所有搜索过的关键字, 最多10个
      keywordsData: [],

      //热搜数据
      hotData: [],

      //是否显示更多热搜数据
      isShowMore: false,

      //初始显示的6条热搜数据
      showCount: 6,

      //热门歌手数据
      hotSongerData: [],

      //搜索关键词数据
      suggestData: [],
    };
  },

  computed: {
    ...mapState([
      "audioId",
      "audioEle",
      "isPaused",
      "songName",
      "songerName",
      "singerId",
      "audioComment",
    ]),
  },

  created() {
    //获取热搜数据
    this.getHotData();

    //获取热门歌手数据
    this.getHotSonger();

    //获取搜索历史记录
    let historySearch = localStorage.getItem("historySearch");

    if (historySearch) {
      this.keywordsData.push(...JSON.parse(historySearch));
    }
  },

  methods: {
    //返回上一级
    goBack() {
      this.$router.go(-1);
    },

    //获取热搜数据
    getHotData() {
      this.axios({
        method: "get",
        url: "/search/hot/detail",
      })
        .then((res) => {
          let hotData = [];
          let hot = {
            //所有热搜数据
            AllhotData: [],

            //初始显示的热搜数据
            ShowhotData: [],
          };

          hot.AllhotData = res.data.data;

          hotData.push(hot);

          //处理控制显示更多按钮的属性
          hotData.forEach((v) => {
            v.showMore = v.AllhotData.length > 6;
            v.ShowhotData.push(...v.AllhotData.slice(0, this.showCount));
          });

          this.hotData = hotData;
        })
        .catch((err) => {
          
        });
    },

    //显示更多商品
    showMorehotData(item) {
      item.ShowhotData.push(...item.AllhotData.slice(this.showCount));
      item.showMore = false;
    },

    //获取热门歌手数据
    getHotSonger() {
      this.axios({
        method: "get",
        url: "/top/artists?offset=0&limit=30",
      })
        .then((res) => {
          this.hotSongerData = res.data.artists;
        })
        .catch((err) => {
          
        });
    },

    //查看歌手页面
    viewSonger(id) {
      this.$router.push({ name: "Songer", params: { id } });
    },

    //输入关键字搜索
    search() {
      //使用函数节流控制触发函数执行的频率
      clearTimeout(this.timer);

      this.suggestData = [];

      this.timer = setTimeout(() => {
        if (this.keywords.trim() === "") {
          return;
        }

        this.axios({
          method: "get",
          url: "/search/suggest",
          params: {
            keywords: this.keywords,
          },
        })
          .then((res) => {
            this.suggestData = res.data.result.songs;

            

            //储存搜索记录
            if (res.data.result.songs.length > 0) {
              //验证是否存在重复的关键字
              for (let i = 0; i < this.keywordsData.length; i++) {
                if (this.keywordsData[i] === this.keywords) {
                  return;
                }
              }

              //是否搜索关键字超出10个, 则移除第一个关键字
              if (this.keywordsData.length === 10) {
                this.keywordsData.splice(0, 1);
              }

              this.keywordsData.push({ title: this.keywords });
              localStorage.setItem(
                "historySearch",
                JSON.stringify(this.keywordsData)
              );
            }
          })
          .catch((err) => {
            
          }, 1000);
      });
    },

    //单个删除关键字
    removeOne(index) {
      this.keywordsData.splice(index, 1);
      localStorage.setItem("historySearch", JSON.stringify(this.keywordsData));
    },

    //删除所有搜索关键字
    clearAll() {
      //清空数组
      this.keywordsData = [];
      localStorage.setItem("historySearch", JSON.stringify(this.keywordsData));
    },

    //mutations
    ...mapMutations(["changeStateProperty"]),

    // 点击播放音频
    playAudio(id, picUrl, songName, songerName, singerId) {
      if (id === this.audioId) {
        if (!this.audioEle.paused) {
          //暂停歌曲
          this.audioEle.pause();
          this.changeStateProperty({ key: "isPaused", value: true });
        } else {
          //播放歌曲
          this.audioEle.play();
          this.changeStateProperty({ key: "isPaused", value: false });
        }
        return;
      }

      //获取音频url
      this.axios({
        method: "get",
        url: "/song/url",
        params: {
          id,
        },
      })
        .then((res) => {
          let audioUrl = res.data.data[0].url;
          this.changeStateProperty({ key: "audioUrl", value: audioUrl });
          this.changeStateProperty({ key: "audioId", value: id });
          //获取暂停状态
          this.changeStateProperty({ key: "isPaused", value: false });
        })
        .catch((err) => {
          
        });

      //获取播放图片
      this.changeStateProperty({ key: "picUrl", value: picUrl });

      this.changeStateProperty({ key: "songName", value: songName });
      this.changeStateProperty({ key: "songerName", value: songerName });
      this.changeStateProperty({ key: "singerId", value: singerId });

      //获取专辑评论数据
      this.axios({
        method: "get",
        url: "/comment/music",
        params: {
          id,
        },
      })
        .then((res) => {
          this.changeStateProperty({
            key: "audioComment",
            value: res.data.hotComments,
          });
        })
        .catch((err) => {
          
        });
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 40px;
}

//搜索框
.back {
  position: relative;
  right: 4px;
  &/deep/.van-icon {
    font-size: 20px;
    font-weight: 600;
  }
}

//热搜榜
.hot,
.hotsonger,
.records {
  background-color: #fff;
  display: flex;
  flex-wrap: wrap;
  padding: 10px 20px;
}

.title {
  width: 100%;
  padding-bottom: 10px;
  font-size: 14px;
  font-weight: 600;
  display: flex;
}

.hotbox {
  width: 100%;
  border-radius: 10px;
  padding: 10px 16px;
  box-shadow: 0 0 0 3px rgba(231, 231, 231, 0.6);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.hotlist {
  width: 145px;
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.name {
  width: 100%;
  display: flex;
  line-height: 24px;
  font-size: 12px;
  font-weight: 600;
}

.icon {
  padding-left: 4px;
  padding-top: 2px;
  width: 26px;
  height: 20px;
  transform: scale(0.6);
}

.icon img {
  width: 22px;
  height: 20px;
}

.txt {
  width: 100%;
  color: rgb(116, 116, 116);
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.showmore {
  width: 100%;
  color: #999999;
  padding: 4px 0 0 0;
  text-align: center;
  border-top: 1px solid rgba(214, 214, 214, 0.7);
}

//热门歌手
.songerlist {
  width: 100%;
  display: flex;
  padding: 4px;
  align-items: center;
  margin-bottom: 14px;
  box-sizing: border-box;
}

.songerphoto {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.songerphoto {
  &/deep/ .van-image__img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
}

.songername {
  padding-left: 10px;
  font-size: 14px;
  font-weight: 600;
}

.go {
  margin-left: auto;
  position: relative;
  left: 10px;
}

//搜索关键词
.suggestlist {
  width: 100%;
  position: absolute;
  top: 54px;
  left: 0;
  right: 0;
  z-index: 99;
  background-color: #fff;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  padding: 10px 16px;
}

.suggestlistbox {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid #9f9f9f5e;
}

.suggesticon {
  width: 20px;
  height: 20px;
  font-size: 20px;
}

.suggestname {
  padding-left: 12px;
  font-size: 14px;
}

//搜索记录
.recordsbox {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid #9f9f9f5e;
}

.recordsleft {
  width: 20px;
  height: 20px;
  font-size: 20px;
}

.recordsname {
  padding-left: 12px;
  font-size: 14px;
}

.recordsright {
  width: 20px;
  height: 20px;
  font-size: 20px;
  margin-left: auto;
}
</style>